package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.Result;
import com.itheima.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * DemoFilter
 *
 * @author liliudong
 * @version 1.0
 * @description DemoFilter
 * @date 2023/7/18 11:25
 */
@Slf4j
// @WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("========================init：初始化Filter========================");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getHeader("Token");
        // 验票操作？
        String url = request.getRequestURL().toString();
        // 如果是登录则放行
        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (!StringUtils.hasText(token)) {
            // 失败了，不放行？
            Result<?> notLogin = Result.error("NOT_LOGIN");
            // 对象变成json串?
            String json = JSON.toJSONString(notLogin);

            response.setContentType("application/json;charset=utf-8");
            // 响应
            response.getWriter().write(json);
            return;
        }

        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            // 失败了，不放行？
            Result<?> notLogin = Result.error("NOT_LOGIN");
            // 对象变成json串?
            String json = JSON.toJSONString(notLogin);

            response.setContentType("application/json;charset=utf-8");
            // 响应
            response.getWriter().write(json);
        }
    }

    @Override
    public void destroy() {
        log.info("========================destroy：销毁Filter========================");

        Filter.super.destroy();
    }
}
